package com.stenio.fancat.service.behavior;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.domain.baby.BabyRelationship;
import com.stenio.fancat.domain.behavior.Behavior;
import com.stenio.fancat.domain.behavior.BehaviorImage;
import com.stenio.fancat.domain.behavior.BehaviorLog;
import com.stenio.fancat.domain.behavior.BehaviorOperationImage;
import com.stenio.fancat.domain.bo.BehaviorBO;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.form.user.UserRelationshipForm;
import com.stenio.fancat.mapper.Behavior.BehaviorImageMapper;
import com.stenio.fancat.mapper.Behavior.BehaviorLogMapper;
import com.stenio.fancat.mapper.Behavior.BehaviorMapper;
import com.stenio.fancat.mapper.Behavior.BehaviorOperationImageMapper;
import com.stenio.fancat.mapper.baby.BabyRelationshipMapper;
import com.stenio.fancat.util.DateUtil;
import com.stenio.fancat.util.RedisUtil;
import com.stenio.fancat.vo.BehaviorVO;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;


@Service
public class BehaviorShowService extends ServiceImpl<BehaviorMapper, Behavior> {

    @Autowired
    private BehaviorMapper behaviorMapper;

    @Autowired
    private BehaviorLogMapper behaviorLogMapper;

    @Autowired
    private BehaviorImageMapper behaviorImageMapper;

    @Autowired
    private BehaviorOperationImageMapper BehaviorOperationImageMapper;

    @Autowired
    private BabyRelationshipMapper babyRelationshipMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${firstPage}")
    private String firstPageKey;


    /**
     * 查询全部任务（首页）  首页展示的图片为用户上传最近的任务照片，没有的话不进行展示
     * @return
     */
    public List<BehaviorVO> selectBehaviorList(UserRelationshipForm userRelationshipForm) throws FanCatException {
        if(null == userRelationshipForm){
            throw new FanCatException("参数异常");
        }

        //根据userId获取babyId
        BabyRelationship babyRelationship = babyRelationshipMapper.selectBabyByUid(userRelationshipForm.getUserId());

        Integer num1 = userRelationshipForm.getCurrentPageNo();
        Integer num2 = userRelationshipForm.getPageSize();

        //判断Redis中是否含有key
        if(null != redisUtil.get(babyRelationship.getBabyId()+firstPageKey+num1+"-"+num2)){
            return (List<BehaviorVO>) redisUtil.get(babyRelationship.getBabyId()+firstPageKey+num1+"-"+num2);
        }


        //查询所有的任务模板
        List<BehaviorBO> list = new ArrayList<>();

        //  MP分页   ---
        Page<Behavior> roleDOList = null;
        List<Behavior> listBehavior = null;
        if(null != userRelationshipForm.getCurrentPageNo() || null != userRelationshipForm.getPageSize()){
            Behavior behavior = new Behavior();
            //limit
            Page<Behavior> page = new Page<>(userRelationshipForm.getCurrentPageNo(),userRelationshipForm.getPageSize());
            Set<String> set = new HashSet<>();
            for(int a = 0;a<page.getSize();a++){
                set.add("create_time");
            }
            Wrapper<Behavior> eWrapper = new EntityWrapper<>(behavior).orderDesc(set).eq("status",1);
            roleDOList = selectPage(page, eWrapper);
            for(int i =0;i<roleDOList.getRecords().size();i++){
                roleDOList.getRecords().get(i).setId(null);
                roleDOList.getRecords().get(i).setStatus(null);
                roleDOList.getRecords().get(i).setParentId(null);
            }
        }else{
            listBehavior = behaviorMapper.selectBehaviorList();
        }

        for(Behavior bo :null == roleDOList ? listBehavior :roleDOList.getRecords()){
            BehaviorBO behaviorBO = new BehaviorBO();
            //所有的任务模板信息
            behaviorBO.setBehavior(bo);
            //如果还未创建baby  把活动的运营图封装进去
            if(null == babyRelationship){
                List<BehaviorImage> images = behaviorImageMapper.selectBehaviorImages(bo.getBehaviorId());
                behaviorBO.setBehaviorImage(images);
            }
            //如果创建了baby
            if(null != babyRelationship){
                //根据babyId查询他所关联的userId
                List<BabyRelationship> listbaby = babyRelationshipMapper.selectUserListByBabyId(babyRelationship.getBabyId());

                //存放每个用户所发布的任务（列表）
                List<BehaviorLog> loglist = new ArrayList<>();

                for(BabyRelationship uid : listbaby){
                    //把每个任务列表拆开，然后add到loglist列表里面
                    List<BehaviorLog> behaviorLogList = behaviorLogMapper.selectBehaviorLogListbyBid(bo.getBehaviorId(),uid.getUserId());
                    for(BehaviorLog bv : behaviorLogList){
                        loglist.add(bv);
                    }
                }

                //把取出的所有的活动取出它们的修改时间，转换后存放到数组里面
                Long[] arr = new Long[loglist.size()];
                for(int i = 0;i<loglist.size();i++){
                    arr[i] = Long.parseLong(DateUtil.format(loglist.get(i).getCreateTime(),"yyyyMMddHHmmss"));
                }
                //进行排序
                Arrays.sort(arr);
                //取出最后一个就是最近发布的那个动态(修改的时间)
                BehaviorLog behaviorLog = null;
                for(int i = 0;i<loglist.size();i++) {
                    Long time = Long.parseLong(DateUtil.format(loglist.get(i).getCreateTime(), "yyyyMMddHHmmss"));
                    if (arr[arr.length - 1]==time.longValue()) {
                        behaviorLog = loglist.get(i);
                        break;
                    }

                }
                if(null != behaviorLog){
                    //查询该任务的任务照片
                    List<BehaviorOperationImage> imageList = BehaviorOperationImageMapper.selectBehaviorOperationImages(behaviorLog.getOperationId());
                    imageList.stream().forEach(image -> {
                        image.setId(null);
                        image.setUpdateTime(null);
                    });
                    behaviorBO.setBehaviorOperationImage(imageList);
                }else{
                    List<BehaviorImage> images = behaviorImageMapper.selectBehaviorImages(bo.getBehaviorId());
                    behaviorBO.setBehaviorImage(images);
                }
            }

            list.add(behaviorBO);
        }
        List<BehaviorVO> behaviorVOList = new ArrayList<>();
        for(BehaviorBO vo : list){
            BehaviorVO behaviorVO = new BehaviorVO();
            try {
                BeanUtils.copyProperties(behaviorVO,vo);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            behaviorVOList.add(behaviorVO);
        }

        //存放Redis中
        redisUtil.set(babyRelationship.getBabyId()+firstPageKey+num1+"-"+num2,behaviorVOList);

        return behaviorVOList;
    }

}
